//
//  IntellectConfigVC.m
//  KEREN
//
//  Created by MW on 2023/3/27.
//

#import "IntellectConfigVC.h"
#import "KRSettingCell.h"
#import "NewsSettingsCell.h"
#import "ElectronicfenceVC.h"
#import "DeviceSetInfo.h"

@interface IntellectConfigVC ()<UITableViewDelegate,UITableViewDataSource,SettingCellDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) int setId;//设置id
@property (nonatomic, strong) DeviceSetInfo *setInfo;
@property (nonatomic, strong) NSMutableArray *itemArray;
@end

@implementation IntellectConfigVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"智能配置"];
    self.setInfo = [[DeviceSetInfo alloc] init];
    self.setInfo.ebike_set = @{@"leave_countdown":@(120),@"vibration_sensitivity":@(2),@"open_lock":@(1),@"open_lock_distance":@(3)};
    NSMutableArray *iArray = @[].mutableCopy;
    SmartItem *item;
    if(self.deviceInfo.deviceConfig.lowerpower){
        item = [SmartItem createSmartItem:@"低电量报警" sub_title:@"" imgName:@"" type:SmartType_LowBattery];
        [iArray addObject:item];
    }
    if(self.deviceInfo.deviceConfig.electric_fence){
        item = [SmartItem createSmartItem:@"电子围栏" sub_title:@"超出设置范围内，即向您发送APP消息" imgName:@"" type:SmartType_Fence];
        [iArray addObject:item];
    }
    item = [SmartItem createSmartItem:@"自动锁车" sub_title:@"无轮动无振动情况下，倒计时多少秒自动关闭车辆" imgName:@"" type:SmartType_AutoLock];
    [iArray addObject:item];
    if(self.deviceInfo.deviceConfig.bluetooth_unlock){
        item = [SmartItem createSmartItem:@"蓝牙靠近解锁" sub_title:@"手机与车辆蓝牙连接成功且设置有效距离范围内，可通过一键启动开关上电/下电车辆" imgName:@"" type:SmartType_NearUnLock];
        [iArray addObject:item];
    }
    if(self.deviceInfo.deviceConfig.sit_induction){
        item = [SmartItem createSmartItem:@"乘坐感应" sub_title:@"座垫感应到您的乘坐重力后，可方启动车辆" imgName:@"" type:SmartType_SitFeel];
        [iArray addObject:item];
    }
    item = [SmartItem createSmartItem:@"震动灵敏度" sub_title:@"支持对车辆的震动报警灵敏度的高低进行设置" imgName:@"" type:SmartType_Vibration_Sensitivity];
    [iArray addObject:item];
    if(self.deviceInfo.deviceConfig.fault_feedback){
        item = [SmartItem createSmartItem:@"故障反馈" sub_title:@"故障信息自动上报到SaaS云平台" imgName:@"" type:SmartType_Problem];
        [iArray addObject:item];
    }
    if(self.deviceInfo.deviceConfig.security_alert){
        item = [SmartItem createSmartItem:@"安全警报" sub_title:@"车辆设防状态下被移动超过一定距离，可能存在被盗风险，自动发送告警消息" imgName:@"" type:SmartType_SaveAlarm];
        [iArray addObject:item];
    }
    self.itemArray = iArray;
    [self tableView];
    [self getDeviceSetting];
}

- (void)getDeviceSetting{
    if([self.deviceInfo is4GDevice]){
        [self getDeviceSettingFrom4G];
    }else{
        [self getDeviceSettingByBLE];
    }
}

-(void)getDeviceSettingFrom4G{
    WEAKSELF
    NSDictionary *parameters = @{@"index":@(1),@"size":@(1),@"ebike_id":@(_ebike_id)};
    [NetworkingTool POST:Device_setting parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        NSDictionary *dict = response[@"data"];
        weakSelf.setId = [dict[@"id"] intValue];
        weakSelf.setInfo = [DeviceSetInfo initWithDictionary:dict];
        [weakSelf.tableView reloadData];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

-(void)getDeviceSettingByBLE{
    WEAKSELF
    [HABleManager bleQueryUnLockDistance:^(HABleModel * _Nonnull bleModel) {
        int v = [bleModel open_lock_distance];
        int time = [bleModel auto_power_off_time];
        NSMutableDictionary *mu_Dict = [NSMutableDictionary dictionaryWithDictionary:weakSelf.setInfo.ebike_set];
        [mu_Dict setValue:@(v > 0 ? 1 : 0) forKey:@"open_lock"];
        [mu_Dict setValue:@(v) forKey:@"open_lock_distance"];
        [mu_Dict setValue:@(time) forKey:@"leave_countdown"];
        weakSelf.setInfo.ebike_set = mu_Dict;
        [weakSelf.tableView reloadData];
    }];
    [HABleManager bleQueryVibrateSensitive:^(HABleModel * _Nonnull bleModel) {
        int v = [weakSelf.deviceInfo is4GDevice] ? ([bleModel fourg_vibration_sensitivity]/400) :  [bleModel vibration_sensitivity];
        DDLogInfo(@"=====vibration_sensitivity is %d",v);
        NSMutableDictionary *mu_Dict = [NSMutableDictionary dictionaryWithDictionary:weakSelf.setInfo.ebike_set];
        [mu_Dict setValue:@(v) forKey:@"vibration_sensitivity"];
        weakSelf.setInfo.ebike_set = mu_Dict;
        [weakSelf.tableView reloadData];
    }];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [UIView new];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01f;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [UIView new];
    return footView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return .01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SmartItem *item = self.itemArray[indexPath.row];
    if(item.type == SmartType_LowBattery){
        return 60;
    }else if(item.type == SmartType_NearUnLock){
        if([_setInfo.ebike_set[@"open_lock"] boolValue]){
            return 190;
        }
        return 80;
    }else if(item.type == SmartType_Vibration_Sensitivity){
        return 150;
    }else if(item.type == SmartType_SaveAlarm){
        return 82;
    }
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SmartItem *item = self.itemArray[indexPath.row];
    if(item.type == SmartType_LowBattery){
        KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
        cell.nameLbl.text = item.title;
        cell.on_offswitch.hidden = YES;
        cell.rightIcon.hidden = NO;
        if(_setInfo){
            cell.decLbl.text = [NSString stringWithFormat:@"%d%@",[_setInfo.ebike_set[@"power_value"] intValue],@"%"];
        }
        return cell;
    }else{
        NewsSettingsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NewsSettingsCell"];
        cell.delegate = self;
        cell.titleLbl.text = item.title;
        cell.isOpenSwitch.hidden = NO;
        cell.bottomView.hidden = YES;
        cell.rightBtn.hidden = YES;
        cell.countLbl.hidden = YES;
        cell.decLbl.numberOfLines = 0;
        if(item.type == SmartType_Fence){
            cell.decLbl.text = item.sub_title;
            cell.isOpenSwitch.hidden = YES;
            cell.rightBtn.hidden = NO;
        }else if(item.type == SmartType_AutoLock){
            cell.decLbl.text = item.sub_title;
            cell.isOpenSwitch.hidden = YES;
            cell.rightBtn.hidden = NO;
            cell.countLbl.hidden = NO;
            cell.countLbl.text = [NSString stringWithFormat:@"%ds",[_setInfo.ebike_set[@"leave_countdown"] intValue]];
        }else if(item.type == SmartType_NearUnLock){
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.bottomView.hidden = NO;
            cell.decLbl.text = item.sub_title;
            cell.isBleLock = YES;
            if([_setInfo.ebike_set[@"open_lock"] boolValue]){
                cell.bottomView.hidden = NO;
                [cell setBottomViewWithIsBleLock:YES andCurrentCount:[_setInfo.ebike_set[@"open_lock_distance"] intValue] - 1];
            }else{
                cell.bottomView.hidden = YES;
            }
            cell.isOpenSwitch.on = [_setInfo.ebike_set[@"open_lock"] boolValue];
        }else if(item.type == SmartType_SitFeel){
            cell.isOpenSwitch.on = _setInfo.fly_car;
            cell.decLbl.text = item.sub_title;
        }else if(item.type == SmartType_Vibration_Sensitivity){
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.isOpenSwitch.hidden = YES;
            cell.decLbl.text = item.sub_title;
            cell.bottomView.hidden = NO;
            cell.isBleLock = NO;
            [cell setBottomViewWithIsBleLock:NO andCurrentCount:[_setInfo.ebike_set[@"vibration_sensitivity"] intValue] - 1];
        }else if(item.type == SmartType_Problem){
            cell.isOpenSwitch.on = [_setInfo.ebike_set[@"hitchs_up"] boolValue];
            cell.decLbl.text = item.sub_title;
        }else if(item.type == SmartType_SaveAlarm){
            cell.isOpenSwitch.on = [_setInfo.ebike_set[@"alarm"] boolValue];
            cell.decLbl.text = item.sub_title;
        }
        cell.isOpenSwitch.tag = item.type + 1000;
        [cell.isOpenSwitch addTarget:self action:@selector(openOrClose:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    SmartItem *item = self.itemArray[indexPath.row];
    if(item.type == SmartType_LowBattery){
        if([self showError]){
            return;
        }
        [[KRAlartManager shareInstance] showPickAlertView:[NSString stringWithFormat:@"低电量设置(%d%@)",[_setInfo.ebike_set[@"power_value"] intValue],@"%"] withcurrentIndex:[_setInfo.ebike_set[@"power_value"] intValue] IscanChooseHistory:NO  changeTitleBlock:^(NSString * _Nonnull title) {
            NSDictionary *dict = @{@"power_value":@([title intValue])};
            NSDictionary *ebike_set = @{@"id":@(self.setId),@"ebike_set":dict};
            [self updateDeviceSettingforSet:nil andEbickSet:ebike_set];
        }];
    }else if(item.type == SmartType_Fence)
    {
        if(![UserInfoManager sharedInstance].currentDeviceInfo){
            [[KRAlartManager shareInstance] showErrorAlert:@"请绑定车辆后再进行操作"];
            return;
        }
        if(_deviceInfo.online_status == 0){
            [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
            return;
        }
        if(!_deviceInfo.is_manager){
            [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        }else{
            ElectronicfenceVC *vc = [[ElectronicfenceVC alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if(item.type == SmartType_AutoLock){
        if([self showError]){
            return;
        }
        WEAKSELF
        [[KRAlartManager shareInstance] showPickAlertView:[NSString stringWithFormat:@"离车自动锁定倒计时(%ds)",[_setInfo.ebike_set[@"leave_countdown"] intValue]] withcurrentIndex:[_setInfo.ebike_set[@"leave_countdown"] intValue] IscanChooseHistory:NO  changeTitleBlock:^(NSString * _Nonnull title) {
            [weakSelf updateAutoLockTime:[title intValue]];
        }];
    }
}

- (BOOL)showError{
    if(![UserInfoManager sharedInstance].currentDeviceInfo.is_manager){
        [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        return YES;
    }
    if(_deviceInfo.online_status == 0 && [_deviceInfo is4GDevice]){
        [[KRAlartManager shareInstance] showErrorAlert:@"车辆已离线"];
        return YES;
    }
    return NO;
}


-(void)updateAutoLockTime:(int)time{
    if([self.deviceInfo is4GDevice]){
        NSDictionary *ebike_set = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"auto_lock_time":@(time)};
        [self send_msgToupdateDeviceSetting:ebike_set];
    }else{
        WEAKSELF
        [HABleManager bleAutoLock:time withCmd:^(HABleModel * _Nonnull bleModel) {
            if(bleModel.step_status == 1){
                NSMutableDictionary *mu_Dict = [NSMutableDictionary dictionaryWithDictionary:self.setInfo.ebike_set];
                [mu_Dict setValue:@(time) forKey:@"leave_countdown"];
                weakSelf.setInfo.ebike_set = mu_Dict;
                [weakSelf.tableView reloadData];
            }else{
                [[KRAlartManager shareInstance] showAlert:@"设置失败"];
            }
        }];
    }
}


- (void)openOrClose:(UISwitch *)sender{
    if([self showError]){
        sender.on = !sender.on;
        return;
    }
    int type = sender.on ? 1 : 0;
    SmartType smart_type = sender.tag - 1000;
    if(smart_type == SmartType_NearUnLock){
        CBPeripheral *peripheral = [HABleManager checkBleConnectedPeripheral:_deviceInfo.sn_code];
        if(peripheral.state != CBPeripheralStateConnected){
            [[KRAlartManager shareInstance] showAlert:@"请先配对蓝牙"];
            sender.on = !sender.on;
            return;
        }
        [HABleManager blErssiIrk:sender.on cmdBlock:^(HABleModel * _Nonnull bleModel) {}];
        if([self.deviceInfo is4GDevice]){
            NSDictionary *ebike_set;
            if(type == 0){
                ebike_set = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"senseless_unlock":@(0)};
            }else{
                ebike_set = @{@"ebike_id":@([UserInfoManager sharedInstance].currentDeviceInfo.Id),@"senseless_unlock":@(3)};
            }
            [self updateDeviceSetting:ebike_set];
        }else{
            NSMutableDictionary *mu_Dict = [NSMutableDictionary dictionaryWithDictionary:self.setInfo.ebike_set];
            [mu_Dict setValue:@(sender.on) forKey:@"open_lock"];
            [mu_Dict setValue:@(sender.on ? 3: 0) forKey:@"open_lock_distance"];
            self.setInfo.ebike_set = mu_Dict;
            WEAKSELF
            [HABleManager bleUnlockDistance:(sender.on ? 3: 0) withCmd:^(HABleModel * _Nonnull bleModel) {
                [weakSelf.tableView reloadData];
            }];
        }
    }else if (smart_type == SmartType_SitFeel){
        NSDictionary *deviceSet = @{@"ebike_id":@(_ebike_id),@"prevent_out_of_control":@(type)};
        [self updateDeviceSetting:deviceSet];
    }
    else if (smart_type == SmartType_Problem){
        NSDictionary *dict = @{@"hitchs_up":@(type)};
        NSDictionary *ebike_set = @{@"ebike_id":@(_setId),@"ebike_set":dict};
        [self updateDeviceSettingforSet:nil andEbickSet:ebike_set];
    }else if (smart_type == SmartType_SaveAlarm){
        NSDictionary *dict = @{@"alarm":@(type)};
        NSDictionary *ebike_set = @{@"ebike_id":@(_setId),@"ebike_set":dict};
        [self updateDeviceSettingforSet:nil andEbickSet:ebike_set];
    }
}

- (void)updateDeviceSetting:(NSDictionary *)dict{
    WEAKSELF
    [NetworkingTool POST:Device_signal_toggle parameters:dict isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf getDeviceSetting];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
    
}

- (void)send_msgToupdateDeviceSetting:(NSDictionary *)dict{
    WEAKSELF
    [NetworkingTool POST:Device_signal_send_msg parameters:dict isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf getDeviceSetting];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}


- (void)updateDeviceSettingforSet:(NSDictionary *)deviceSet andEbickSet:(NSDictionary *)dcit{
    NSDictionary *parameters;
    if(deviceSet){
        parameters = deviceSet;
    }else{
        parameters = dcit;
    }
    WEAKSELF
    [NetworkingTool POST:Device_setting_update parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf getDeviceSetting];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        
    }];
}

- (void)bottomViewClick{
    [[KRAlartManager shareInstance] showPickAlertView:@"蓝牙强度" withcurrentIndex:[_setInfo.ebike_set[@"open_lock_distance"] intValue] - 1 IscanChooseHistory:NO   changeTitleBlock:^(NSString * _Nonnull title) {
        int type = 0;
        if([title isEqualToString:@"强"]){
            type = 3;
        }else if ([title isEqualToString:@"中"]){
            type = 2;
        }else{
            type = 1;
        }
        NSDictionary *ebike_set = @{@"ebike_id":@(self.ebike_id),@"senseless_unlock":@(type)};
        [self updateDeviceSetting:ebike_set];
    }];
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRSettingCell" bundle:nil] forCellReuseIdentifier:@"KRSettingCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"NewsSettingsCell" bundle:nil] forCellReuseIdentifier:@"NewsSettingsCell"];

        [self.view addSubview:_tableView];
    }
    return _tableView;
}

#pragma mark-SettingCellDelegate
-(void)sureSwitch:(UITableViewCell *)cell gear:(int)gear{
    NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
    SmartItem *item = self.itemArray[indexPath.row];
    NSMutableDictionary *mu_Dict = [NSMutableDictionary dictionaryWithDictionary:self.setInfo.ebike_set];
    if(item.type == SmartType_NearUnLock){
        [mu_Dict setValue:@(gear) forKey:@"open_lock_distance"];
    }else if(item.type == SmartType_Vibration_Sensitivity){
        [mu_Dict setValue:@(gear) forKey:@"vibration_sensitivity"];
    }
    self.setInfo.ebike_set = mu_Dict;
}
@end
